package com.reflex;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class IntrospectorDemo1 {

    public static void main(String[] args) throws IllegalAccessException, IntrospectionException, InvocationTargetException {
        Person p1 = new Person("张三",18);
        Object obj = IntrospectorDemo1.getProperty(p1,"name");
        System.out.println(obj);
        IntrospectorDemo1.setProperty(p1,"name","里斯");
        System.out.println(p1.getName());

        listProperty(p1);
    }

    private static void listProperty(Object obj) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
        //如果不想把父类的属性也列出来的话，
        //那getBeanInfo的第二个参数填写父类的信息
        BeanInfo info = Introspector.getBeanInfo(obj.getClass(),Object.class);
        PropertyDescriptor[] pds = info.getPropertyDescriptors();
        for (int i = 0; i < pds.length; i++) {
            PropertyDescriptor pd = pds[i];
            System.out.println(pd.getName()+":"+pd.getReadMethod().invoke(obj));
        }
    }

    private static void setProperty(Object obj,String propertyName,Object value) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
        PropertyDescriptor pd = new PropertyDescriptor(propertyName,obj.getClass());
        Method serMethod = pd.getWriteMethod();
        serMethod.invoke(obj,value);
    }

    private static Object getProperty(Object obj,String propertyName) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
        PropertyDescriptor pd = new PropertyDescriptor(propertyName,obj.getClass());
        Method getMethod = pd.getReadMethod();
        return getMethod.invoke(obj);
    }

    static class Person{
        private String name;
        private int age;

        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}
